package com.disdr.utils;


import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;


public class LettuceRedis {

    /**
     * 设置Redis缓存
     * @param key
     * @param val
     */
    public static void set(String key, String val){
        getRedis().set(key,val);
    }
    /**
     * 设置Redis缓存(有效期*秒)
     * @param key
     * @param val
     */
    public static void setExpire(String key, String val, long time){
        RedisCommands<String, String> syncCommands = getRedis();
        syncCommands.set(key,val);
        syncCommands.expire(key,time);
    }

    /**
     * 获取Redis缓存
     * @param key
     */
    public static String get(String key){
        return getRedis().get(key);
    }

    public static RedisCommands<String, String> getRedis(){
        // 连接到本地的Redis服务器，默认端口6379
        RedisClient redisClient = RedisClient.create("redis://localhost");
        StatefulRedisConnection<String, String> connection = redisClient.connect();

        // 同步操作
        RedisCommands<String, String> syncCommands = connection.sync();

        return syncCommands;
    }

    public static void main(String[] args) {
        // 连接到本地的Redis服务器，默认端口6379
        RedisClient redisClient = RedisClient.create("redis://localhost");
        StatefulRedisConnection<String, String> connection = redisClient.connect();

        // 同步操作
        RedisCommands<String, String> syncCommands = connection.sync();

        // 设置键值对
        syncCommands.set("key", "value");

        // 获取键对应的值
        String value = syncCommands.get("key");
        System.out.println("key: " + value);

        // 关闭连接
        connection.close();
        redisClient.shutdown();
    }
}
